package org.dant.ant.extension.tasks;

import java.io.*;
import java.util.*;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.xml.XMLResultFormatter;

public class TestSuite extends Task implements TaskContainer {
    protected String name;

    protected List nestedTasks = new LinkedList();
  
    protected boolean printSummary;

    protected File resultdir;

    protected boolean isSuccess = true;

    private XMLResultFormatter formatter = new XMLResultFormatter();

    public void setResultdir(File dir) {
        this.resultdir = dir;
    }

    public File getResultdir() {
        if (resultdir == null) {
            return getProject().getBaseDir();
        }
        return this.resultdir;
    }
  
    public String getName() {
        if (this.name == null) {
            return "default test sutie";
        }
        return this.name;
    }

    public void setName(String n) {
        this.name = n;
    }

    public void setPrintsummary(boolean p) {
        this.printSummary = p;
    }

    public boolean getPrintsummary() {
        return this.printSummary;
    }


    public boolean isSuccess() {
        return this.isSuccess;
    }
  
    public void addTask(Task nestedTask) {
        nestedTasks.add(nestedTask);
    }

    protected void exportResult(RemoteResponse results) {
        formatter.writeResults(results, getResultdir());    
    }

    public void execute() throws BuildException {
        System.out.println("Running TestSuite: " + this.name);

        for (Iterator iter = nestedTasks.iterator(); iter.hasNext();) {
            Task task = (Task) iter.next();
            if (task instanceof TestCase) {
                TestCase testcase = (TestCase) task;
                testcase.setOwningTestSuite(this);
                if (!testcase.isSuccess()) {
                    this.isSuccess = false;
                }
                testcase.perform();
                exportResult(new RemoteResponse(testcase.getName(), this.name, RemoteResponse.TESTCASE, testcase.isSuccess()));
            } else {
                task.perform();
            }
        }
    }
}
